
//
// JSDB
//

writeFile = function(filename, text) {
	var file;
	writeCounter++;
	try {
		file = new Stream(filename, 'tw+');
		file.write(text);
		file.flush();
	} catch(e) {
		echo('Unable to write to ' + filename + '.');
		writeCounter--;
	}
	file = null;
}

readBinFile = function(filename) {
	var data = [];
	try {
		var file = new Stream(filename, 'rb');
		while (file.canRead())
			data.push(file.readByte());
	} catch(e) {
		echo('Unable to read binary data from ' + filename + '. Error msg: ' + e.message);
	}
	return data;
}

writeBinFile = function(filename, data) {
	writeCounter++;
	try {
		var file = new Stream(filename, 'wb');
		for (var i = 0; i < data.length; i++)
			file.writeByte(data[i]);
		file.flush();
	} catch(e) {
		echo('Unable to write binary file ' + filename + '. Error msg: ' + e.message);
		writeCounter--;
	}
}

listFiles = function(folder, extension, prefix) {
	var vec = [], ext, pre;
	if (arguments.length > 1) rx = new RegExp('\\.' + extension + '$');
	if (arguments.length > 2) pre = new RegExp('^' + prefix + '\\.');
	var v = system.files(folder);
	for (var i = 0; i < v.length; i++) {
		var name = v[i];
		if (arguments.length < 2 || (rx.test(name) && (arguments.length < 3 || pre.test(name))) )
			vec.push(name);
	}
	return vec;
}

getFileSize = function(filePath) {
	try {
		return new Stream(filePath, 'rb').size;
	} catch(e) { }
	return null;
}

ensurePathExists = function(filepath) {
	system.mkdir(filepath);
}

copyFile = function(source, target) {
	system.copy(source, target);
}

fileExists = function(filename) {
	system.exists(filename);
}

deleteFile = function(filename) {
	system.remove(filename);
}

deleteFolder = function(folder) {
	system.remove(folder);
}

copyFolder = function(source, target) {
	system.copy(source, target);
}

args = [];
for (var i = 0; i < system.arguments.length; i++)
	args[i] = system.arguments[i];
